import { defineComponent, reactive } from 'vue'
import Docker from '@/components/Docker'
import { getOrdersApi } from '@/api/order'
import { Order } from '@/types/model'

interface OrdersData {
  list: Order[]
}

/* 处理订单列表逻辑 */
const useOrderListEffect = () => {
  const data: OrdersData = reactive({
    list: []
  })

  const getOrders = async () => {
    const res = await getOrdersApi()
    if (res.code === 0) {
      data.list = res.data
    }
  }

  getOrders()

  return {
    data
  }
}

export default defineComponent({
  name: 'OrderList',
  setup () {
    const { data } = useOrderListEffect()
    /* render 函数 */
    return () => {
      const orders = data.list.map(order => {
        const productImgs = order.products.slice(0, 4).map(product => (
          <img src={ product.product.imgUrl } />
        ))
        const price = order.products.reduce((total, product) => {
          total += product.orderSales * product.product.price
          return total
        }, 0)
        return (
          <div class="order">
            <div class="order__title">
              { order.shopName }
              <span class="order__status">{ order.isCanceled ? '已取消' : '已下单' }</span>
            </div>
            <div class="order__content">
              <div class="order__content__imgs">
                { productImgs }
              </div>
              <div class="order__info">
                <div class="order__info__price">￥{ price }</div>
                <div class="order__info__count">共{ order.products.length }件</div>
              </div>
            </div>
          </div>
        )
      })
      return (
        <>
          <div class="order__list">
            <div class="title">我的订单</div>
            <div class="orders">
              { orders }
            </div>
          </div>
          <Docker currentIndex={ 2 } />
        </>
      )
    }
  }
})
